//
//  MarketingAnalysisViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/8/21.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

class MarketingAnalysisViewController: BaseViewController {

    var companys: Array<JSON> = []
    
    var father: NewAnalysisContainerViewController?
    
    @IBOutlet weak var companyField: UITextField!
    
    var selectedCompany = ""
    
    var detailPath = SaleStastic
    
    @IBOutlet weak var targetAmount: UILabel!
    
    @IBOutlet weak var saleAmount: UILabel!
    
    @IBOutlet weak var contractAmount: UILabel!
    
    @IBOutlet weak var contractBackAmount: UILabel!
    
    @IBOutlet weak var inputField: UITextField!
    
    @IBOutlet weak var firstLabel: UILabel!
    
    @IBOutlet weak var secondLabel: UILabel!
    
    @IBOutlet weak var thirdLabel: UILabel!
    
    @IBOutlet weak var forthLabel: UILabel!
    
    @IBAction func chooseCompany(_ sender: Any) {
        
        popalert()
        
    }
    
    
    @IBOutlet weak var amountLbl: UILabel!
    
    @IBAction func tenderAction(_ sender: UIButton) {
        
        let destinate = ProjectDetailChartViewController()
        
        destinate.selectedDate = self.father!.endDate()
        
        destinate.title = self.lbls[0].text
        
        destinate.companys = self.companys
        
        destinate.selectedCompany = self.selectedCompany
        
        destinate.key = "biddingInfo"
        
        self.father!.push(destination: destinate)
        
    }
    
    @IBAction func saleAction(_ sender: UIButton) {
        
        let destinate = ProjectDetailChartViewController()
        
        destinate.selectedDate = self.father!.endDate()
        
        destinate.candetail = true
        
        destinate.title = self.lbls[1].text
        
        destinate.companys = self.companys
        
        destinate.selectedCompany = self.selectedCompany
        
        destinate.key = "marketingcontract"
        
        self.father!.push(destination: destinate)
        
    }
    
    @IBAction func tickAction(_ sender: UIButton) {
        let destinate = ProjectDetailChartViewController()
        
        destinate.selectedDate = self.father!.endDate()
        
        destinate.title = self.lbls[2].text
        
        destinate.companys = self.companys
        
        destinate.selectedCompany = self.selectedCompany
        
        destinate.key = "openingInvoiceRecord"
        
        self.father!.push(destination: destinate)
        
    }
    
    @IBAction func ticketBackAction(_ sender: UIButton) {
        
        let destinate = ProjectDetailChartViewController()
        
        destinate.selectedDate = self.father!.endDate()
        
        destinate.title = self.lbls[3].text
        
        destinate.companys = self.companys
        
        destinate.selectedCompany = self.selectedCompany
        
        destinate.key = "backCapitalService"
        
        self.father!.push(destination: destinate)
        
    }
    
    @IBAction func shouldIncomeAction(_ sender: Any) {
        
    }
    
    
    func loadOrg() -> Void {
        load(with: "JYYSK")
        load(with: "GetOrg")
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        loadOrg()
        
        NotificationCenter.default.addObserver(self, selector: #selector(dateChange(not:)), name: NSNotification.Name("DateChange"), object: nil)
    }
    
    @objc func dateChange(not: Notification) {
        self.load(with: "Detail")
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.father!.view.endEditing(true)
    }
    
    
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        if self.companys.count > 0 {
//            NetManager.get(detailPath, self.param(for: "Detail"), suc: { (json) in
//                self.success(for: "Detail")(json);
//            }) { (error) in
//                self.alert(error.localizedDescription)
//            }
//        }
//    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override var names: Array<String> {
        get{
            return ["GetOrg","Detail"]
        }
    }
    
    @IBOutlet var lbls: [UILabel]!
    
    override func success(for name: String) -> NetSuccess{
        
        func getOrgSuc(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    companys = data
                    if companys.count > 0 {
                        let item = companys[0]
                        selectedCompany = item.contents!["code"]!.rawString()!
                        self.companyField.text = item.contents?["name"]?.rawString()
                        self.load(with: "Detail")
                    }
                    
                }
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        func detail(json: JSON)->Void{
            
            if json.contents?["success"]?.bool == true {
                
                if let data = json.contents?["data"]?.contents {
                    
                    let first = data["biddingInfo"]?.contents?["yearCount"]?.int ?? 0
                    self.lbls[0].text = data["biddingInfo"]?.contents?["typeTitle"]?.rawString()
                    
                    let firthMonth = data["biddingInfo"]?.contents?["monthCount"]?.int ?? 0
                    
                    let second = data["marketingcontract"]?.contents?["yearCount"]?.int ?? 0
                    self.lbls[1].text = data["marketingcontract"]?.contents?["typeTitle"]?.rawString()
                    
                    let secondMonth = data["marketingcontract"]?.contents?["monthCount"]?.int ?? 0
                    
                    let third = data["openingInvoiceRecord"]?.contents?["yearCount"]?.int ?? 0
                    
                    self.lbls[2].text = data["openingInvoiceRecord"]?.contents?["typeTitle"]?.rawString()
                    
                    let thirdMonth = data["openingInvoiceRecord"]?.contents?["monthCount"]?.int ?? 0
                    
                    let forth = data["backCapitalService"]?.contents?["yearCount"]?.int ?? 0
                    self.lbls[3].text = data["backCapitalService"]?.contents?["typeTitle"]?.rawString()
                    
                    let forthMonth = data["backCapitalService"]?.contents?["monthCount"]?.int ?? 0
                    self.targetAmount.text = String(format: "%i", first / 1000000).rmbformat
                    
                    self.firstLabel.text = "当月" + String(format: "%i", firthMonth / 1000000).rmbformat + "万元"
                    
                    self.saleAmount.text = String(format: "%i", second / 1000000 ).rmbformat
                    self.secondLabel.text = "当月" + String(format: "%i", secondMonth / 1000000).rmbformat + "万元";
                    
                    self.contractAmount.text = String(format: "%i", third / 1000000).rmbformat
                    self.thirdLabel.text = "当月" + String(format: "%i", thirdMonth / 1000000).rmbformat + "万元"
                    
                    self.contractBackAmount.text = String(format: "%i", forth / 1000000).rmbformat
                    self.forthLabel.text = "当月" + String(format: "%i", forthMonth / 1000000).rmbformat + "万元"
                    
                    let endMoneyMonth = data["getEndMoney"]?.contents?["monthCount"]?.int ?? 0
                    let getEndMoney = data["getEndMoney"]?.contents?["yearCount"]?.int ?? 0
                    
                    self.amountLbl.text = String(format: "%i", getEndMoney / 1000000).rmbformat
                    self.endMoneyMonthLbl.text = "当月" + String(format: "%i", endMoneyMonth / 1000000).rmbformat + "万元"
                }
            }else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        
        func needReceive(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.int {
                    let real = (data / 1000000)
                    let str = String(real).rmbformat
                    self.amountLbl.text = str
                }
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        if name == "GetOrg" {
            return getOrgSuc
        } else if name == "JYYSK" {
            return needReceive
        } else {
            return detail
        }
    }
    
    @IBOutlet weak var endMoneyMonthLbl: UILabel!
    override func param(for name: String) -> Dictionary<String,Any>{
        if name == "GetOrg" {
            return [:]
        } else if name == "Detail" {
            return ["orgCode":self.selectedCompany,"endDate": self.father!.endDate()]
        }
        return [:]
    }
    
    override func path(for name: String) -> String{
        if name == "GetOrg" {
            return GETORG
        } else {
            return detailPath
        }
    }
    
    override func method(for name: String) -> NetMethod{
        return .get
    }
    
    //响应接口的有效性策略,如果参数不合格，则默认根据String提示
    override func strategy(for name: String) -> (Bool,String?,(()->Void)?){
        return (true,nil,nil)
    }

    @objc func popalert() -> Void {
        
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                
                self.companyField.text = item.contents?["name"]?.rawString()
                
                self.selectedCompany = item.contents?["code"]?.rawString() ?? ""
                
                self.load(with: "Detail")
            }
            alert.addAction(sheet)
        }
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    
}
